from functools import partial

from fastapi.templating import Jinja2Templates
from fastapi.requests import Request

from utils.i18n.i18n import i18n
from utils.enums import Language
from utils.template.filter import trim, format_datetime_object
from utils.template.function import current_year

templates = Jinja2Templates(directory="web/templates")


def register_template():
    # 注册过滤器
    templates.env.filters['trim'] = trim
    templates.env.filters['format_datetime_object'] = format_datetime_object

    # 注册全局函数
    templates.env.globals["current_year"] = current_year


# 响应模板参数
def template(request: Request, t: str, context: dict, status_code: int = 200):
    return templates.TemplateResponse(
        t,
        context={
            "request": request,
            "lang": "zh-CN" if request.state.language == Language.CN else "en",
            "i18n": partial(i18n, language=request.state.language),
            "site_info": request.state.site_info if hasattr(request.state, "site_info") else None,
            "product_type_list": request.state.product_type_list if hasattr(request.state, "product_type_list") else None,
            "news_type_list": request.state.news_type_list if hasattr(request.state, "news_type_list") else None,
            "nestest_news_items": request.state.nestest_news_items if hasattr(request.state, "nestest_news_items") else None,
            **context
        },
        status_code=status_code
    )
